package com.hankol.winecellar

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Environment
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.bumptech.glide.Glide
import com.hankol.winecellar.adapter.ShareWineMealPosterAdapter
import com.hankol.winecellar.bean.WineCellarPosterParams
import com.hankol.winecellar.databinding.ActivityWineCellarPosterBinding
import com.hankol.winecellar.utils.FlexBoxUtils
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import com.transitionseverywhere.TransitionManager
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * @description 分享-酒窖详情海报
 * @time 2022/6/30 9:58 下午
 */
@Route(path = ActivityRouter.WINE_CELLAR.SHARE_POSTER)
class WineCellarPosterActivity : BaseActivity() {

    companion object {
        const val KEY_WINERY_DATA_INFO = "KEY_WINERY_POSTER_DATA"
    }

    private lateinit var dataBinding: ActivityWineCellarPosterBinding
    private lateinit var mViewModel: WineCellarViewModel
    private var isPreserve: Boolean = false
    private var filePath: String = ""
    private var position: Int = -1
    var mDataBean: WineCellarPosterParams? = null

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_wine_cellar_poster
    }

    override fun init() {
        intent.extras?.let {
            mDataBean = getParcelable<WineCellarPosterParams>(KEY_WINERY_DATA_INFO)
        }
        dataBinding = getDataBinding<ActivityWineCellarPosterBinding>()
        mViewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        //加载背景图
        Glide.with(applicationContext).load(mDataBean?.bgCover.checkValue()).placeholder(R.drawable.ic_def_hanxiang_228).apply(dataBinding.ivWineMealPosterBg.setGaussBlur()).into(dataBinding.ivWineMealPosterBg)
        setView()
        initListener()
        dataBinding.rcivWineryCover.load(this@WineCellarPosterActivity, mDataBean?.bgCover.checkValue())

    }

    fun initListener() {
        dataBinding.imgCancel.setOnClickListener { finish() }
    }

    @SuppressLint("SetTextI18n") fun setView() {
        dataBinding.apply {
            mDataBean?.let {
                tvWineryName.text = it.title.checkValue()
                tvPrice.text = "¥${it.price}/人"
                rcivWineryCover.load(this@WineCellarPosterActivity, it.bgCover.checkValue())
                tvAddress.text = it.address.checkValue()
                //标签
                flLabel.removeAllViews()
                val labelList = arrayListOf<String>()
                if (it.label.size > 3) {
                    labelList.clear()
                    labelList.addAll(it.label.subList(0, 3))
                } else {
                    labelList.addAll(it.label)
                }
                for (bean in labelList) {
                    FlexBoxUtils.addChildToFlexboxLayoutD8(flLabel, bean)
                }
                ivQrcode.load(this@WineCellarPosterActivity, it.qrCode.checkValue())
            }
        }
        loadData()
    }

    private fun loadData() {
        TransitionManager.beginDelayedTransition(dataBinding.llWineMealPoster)
        dataBinding.llShare.visibility = View.VISIBLE
        dataBinding.rvWineMealPosterLayout.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        val mSharePosterAdapter = ShareWineMealPosterAdapter()
        dataBinding.rvWineMealPosterLayout.adapter = mSharePosterAdapter

        mSharePosterAdapter.setListener { position ->
            this.position = position
            if (!DoubleClickHelper.isOnDoubleClick()) {
                if (filePath.checkNotNull()) {
                    LoadingManager.showLoadingDialog(this)
                    share()
                } else {
                    dataBinding.rlWinePoster.post {
                        GlobalScope.async {
                            createPoster()
                        }
                    }
                }
            }
        }
    }

    fun share() {
        if (position != -1) {
            if (position != 2) {
                LoadingManager.hideLoadingDialog(this)
                UMShareUtils.shareImageLocalFile(this, if (position == 0) SHARE_MEDIA.WEIXIN else SHARE_MEDIA.WEIXIN_CIRCLE, filePath.checkValue())
            } else {
                if (!TextUtils.isEmpty(filePath)) {
                        StorageUtils.saveImageToGallery(this, filePath, object : StorageUtils.ISaveCallback {
                            override fun saveSuccess() {
                                isPreserve = true
                                dataBinding.rlWinePoster.postDelayed(Runnable {
                                    LoadingManager.hideLoadingDialog(this@WineCellarPosterActivity)
                                    ToastUtils.showShort(this@WineCellarPosterActivity, "海报已下载到相册")
                                }, 200)
                            }
                        })
                }
            }
        }
    }

    override fun onDestroy() {
        if (!isPreserve) {
            if (filePath.isNotEmpty()) {
                File(filePath).delete()
            }
        }
        super.onDestroy()
    }

    /**
     * 保存图片到图库
     *
     * @param bmp
     */
    private fun saveImageToGallery(bmp: Bitmap?) {
        if (bmp == null) return
        // 首先保存图片 创建文件夹
        val appDir = File(Environment.getExternalStorageDirectory(), "hanke_share")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        //图片文件名称
        val fileName = "hanke_share" + System.currentTimeMillis() + ".jpg"
        val mFile = File(appDir, fileName)
        var fos: FileOutputStream? = null
        try {
            fos = FileOutputStream(mFile)
            bmp.compress(Bitmap.CompressFormat.PNG, 30, fos)

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (fos != null) {
                try {
                    fos.flush()
                    fos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        //        //把文件插入到系统图库
        filePath = mFile.absolutePath
        share()
    }

    fun createPoster() {
        val bitmap = BitmapUtils.convertViewToBitmap(dataBinding.rlWinePoster);
        saveImageToGallery(bitmap)
    }

}